package com.cloudcc.mobile.view.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.cloudcc.mobile.view.dynamic.SendTimeLineActivity;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.DraftBoxAdapter;
import com.cloudcc.mobile.adapter.DraftBoxAdapter.OnSendListener;
import com.cloudcc.mobile.db.DraftBoxDB;
import com.cloudcc.mobile.entity.ImageInfo;
import com.cloudcc.mobile.entity.Khbf;
import com.cloudcc.mobile.entity.ManyImage;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostMessage;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.chat.DraftKhbf;
import com.cloudcc.mobile.entity.comment.AddMicroComment;
import com.cloudcc.mobile.entity.comment.AddMicroCommentMessage;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.AddMicroCommentParser;
import com.cloudcc.mobile.parser.AddMicroPostMessageParser;
import com.cloudcc.mobile.parser.ImageParser;
import com.cloudcc.mobile.parser.KhbfParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UploadClient;
import com.cloudcc.mobile.util.UploadImgManyClient;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.utils.SaveTemporaryData;

/**
 * 草稿箱
 *
 * @author Administrator
 */
public class DraftBoxActivity extends BaseActivity {
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private SwipeMenuListView listView;
    private Context context;
    private List<DraftBox> boxlist;
    private DraftBoxAdapter adapter;
    private ImageView fanhui;
    private DraftBox box;
    private List<String> pzlist = new ArrayList<String>();
    private String[] stringpz;
    private String[] pclist;
    private DraftKhbf draftkhbf;
    private List<String> imgpath;
    private List<String> pcpath;
    private int listposition;
    private AddMicroPostF addMicroPostF;
    private AddMicroPostDMany addMicroPostDMany;
    private AddMicroPostL addMicroPostL;
    private AddMicroPostV addMicroPostV;
    private AddMicroPostDMany bbbb;
    private String leixing;
    AddMicroComment comment;
    private int isToast = 0;
    private int p;
    private float dx;
    private float ux;
    private Button btnBtn;
    public int deletePosition;

    public Button btnBacks;

    /**
     * @param lyj 2017-07-18 pm
     */
    private LinearLayout backLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        fanhui = (ImageView) findViewById(R.id.imgBacks);
        btnBacks = (Button) findViewById(R.id.btnBacks);
        btnBacks.setVisibility(View.GONE);
        listener();
        try {
            context = this.getApplicationContext();
            setupView();
            addListener();
        } catch (Exception e) {
            Tools.handle(e);
        }

    }
    public void listener(){
        btnBacks.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        // 返回按钮监听
        fanhui.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.draftbox_list;
    }

    /**
     * 滑动返回
     */
//	@Override
//	public boolean dispatchTouchEvent(MotionEvent ev) {
//		// 当按下时处理
//		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//			dx = ev.getX();
//		} else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
//			ux = ev.getX();
//			if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
//					&& ux > dx) {
//				finish();
//				// 设置切换动画，从右边进入，左边退出
//				overridePendingTransition(R.anim.in_from_left,
//						R.anim.out_to_right);
//			}
//		}
//		return super.dispatchTouchEvent(ev);
//	}

    /**
     * 做监听
     */
    public boolean isBool = true;

    private void addListener() {

        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {

                switch (index) {
                    case 0:
                        // open   点击删除之后立马调用的方法
                        deleteItem(position);
                        break;
                    case 1:
                        // delete
                        Toast.makeText(mContext, "DDDDDDDDDDDDDDDDDDDDD", 1).show();
                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });
        btnBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (isBool) {
//                    allShow();
//                } else {
//                    allHint();
//                }

            }
        });


        adapter.setmItemOnClickListener(new DraftBoxAdapter.ItemOnClickListener() {
            @Override
            public void itemOnClickListener(View view, int position) {
//                deleteItem(position);
                listView.smoothOpenMenu(position);
                allShow();
            }
        });



        /**
         * adapter监听
         */
        adapter.setOnSendListener(new OnSendListener() {
            @Override
            public void send(int position, View v) {
                v.setClickable(false);
                listposition = position;
                box = adapter.getItem(position);
                boxlist.get(listposition).setClickable(false);
                p = position;
                adapter.changData(boxlist);


                if ("en".equals(mEns)) {
                    if (box.getType().equals("1")) {
                        NotificationUtils.showNotification(context, "Sending...", "Check in",
                                "Sign in to send...", position);
                        sendQianDao(position);
                    } else if (box.getType().equals("2")) {
                        NotificationUtils.showNotification(context, "Sending...", "Micro-paste",
                                "Micro stickers sent...", p);
                        sendWeiBo(position, v);
                    } else if (box.getType().equals("3")) {
                        NotificationUtils.showNotification(context, "Sending...", "Reply",
                                "Reply to send...", p);
                        sendComment();
                    }
                } else {
                    if (box.getType().equals("1")) {
                        NotificationUtils.showNotification(context, "发送中...", "签到",
                                "签到发送中...", position);
                        sendQianDao(position);
                    } else if (box.getType().equals("2")) {
                        NotificationUtils.showNotification(context, "发送中...", "微贴",
                                "微贴发送中...", p);
                        sendWeiBo(position, v);
                    } else if (box.getType().equals("3")) {
                        NotificationUtils.showNotification(context, "发送中...", "回复",
                                "回复发送中...", p);
                        sendComment();
                    }
                }

            }

            @Override
            public void listviewbtn(int position) {
            }

            @Override
            public void LongClicked(ContextMenu menu, int position) {
                listposition = position;
                // menu.setHeaderTitle("草稿箱操作");


                if ("en".equals(mEns)) {
                    menu.add(1, 200, 1, "Delete this information");
                    menu.add(1, 201, 2, "Clear the draft box");
                } else {
                    menu.add(1, 200, 1, "删除此信息");
                    menu.add(1, 201, 2, "清空草稿箱");
                }

            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                showCenterPopupWindow(backLayout,i);
                return true;
        }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DraftBox box = boxlist.get(i);
                String text = "";
                if (box.getLeixing().equals("addMicroPostF")) {
                    text = box.getAddMicroPostF().getBody();
                } else if (box.getLeixing().equals("addMicroPostDMany")) {
                    text = box.getAddMicroPostDMany().getBody();
                } else if (box.getLeixing().equals("addMicroPostL")) {
                    text = box.getAddMicroPostL().getBody();
                } else if (box.getLeixing().equals("addMicroPostV")) {
                    text = box.getAddMicroPostV().getBody();
                }
                Intent intent = new Intent(DraftBoxActivity.this, SendTimeLineActivity.class);
                intent.putExtra("content", text);
                startActivity(intent);
                deletePosition = i;


            }

        });
//        listView.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
//            @Override
//            public void onMenuOpen(int position) {
////                statShowBtn(position);
//            }
//
//            @Override
//            public void onMenuClose(int position) {
////                statHintBtn(position);
//            }
//        });
    }


    public void deleteItem(int listposition) {
        DraftBox box = adapter.getItem(listposition);
        try {

            db.deleteById(DraftBox.class, box.getId());
            boxlist = db.findAllDraftBox(DraftBox.class);
            adapter.changData(boxlist);
            Intent caogao = new Intent(AppContext.CAOGAO_NUM);
            sendBroadcast(caogao);
        } catch (DbException e) {
            Tools.handle(e);
        }
    }

    public void deleteAllItem() {
        try {
            db.deleteAll(DraftBox.class);
            boxlist = db.findAllDraftBox(DraftBox.class);
            adapter.changData(boxlist);
            Intent caogao = new Intent(AppContext.CAOGAO_NUM);
            sendBroadcast(caogao);
        } catch (DbException e) {
            Tools.handle(e);
        }
    }


    // 上下文菜单
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();
        DraftBox box = adapter.getItem(listposition);
        switch (item.getItemId()) {
            case 200:
                try {

                    db.deleteById(DraftBox.class, box.getId());
                    boxlist = db.findAllDraftBox(DraftBox.class);
                    adapter.changData(boxlist);
                    Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                    sendBroadcast(caogao);
                } catch (DbException e) {
                    Tools.handle(e);
                }
                break;
            case 201:
                try {
                    db.deleteAll(DraftBox.class);
                    boxlist = db.findAllDraftBox(DraftBox.class);
                    adapter.changData(boxlist);
                    Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                    sendBroadcast(caogao);
                } catch (DbException e) {
                    Tools.handle(e);
                }
                break;

            default:
                break;
        }

        return super.onContextItemSelected(item);
    }

    // 签到
    protected void sendQianDao(final int position) {
        isToast = 0;
        draftkhbf = box.getKhbf();
        String pzs = draftkhbf.getPz();
        stringpz = pzs.split(",");
        imgpath = new ArrayList<String>();
        for (int i = 0; i < stringpz.length; i++) {
            File file = new File(stringpz[i]);
            if (file.exists()) {
                imgpath.add(stringpz[i]);
            }
        }
        final String[] imagepaths = new String[imgpath.size()];
        for (int i = 0; i < imgpath.size(); i++) {
            imagepaths[i] = imgpath.get(i);
        }
        if (imgpath.size() > 0) {// 有图的时候
            ManyImage images = new ManyImage();
            images.setImgName(Tools.getTimeName(System.currentTimeMillis()));
            images.setImgHeight("");
            images.setImgWidth("");
            images.setImgId("");
            images.setImgType("png");
            final String data = Json.toJson(images);
            new Thread() {
                public void run() {
                    try {
                        String result = null;
                        String Data = URLDecoder.decode(data, "UTF-8");
                        final String url = UrlTools.url
                                + UrlTools.imgupload_path + Data + "&binding="
                                + AppContext.binding;
                        result = UploadClient.sendMany(imagepaths, url);
                        if (result != null) {
                            Message msg = handler.obtainMessage(1);
                            msg.obj = result;
                            msg.arg1 = position;
                            msg.sendToTarget();
                        } else {
                            Message msgMessage = handler.obtainMessage(-3);
                            msgMessage.arg1 = position;
                            msgMessage.sendToTarget();
                            return;
                        }
                    } catch (Exception e) {
                        Tools.handle(e);
                    }
                }
            }.start();
        } else {// 没有图片的时候
            Message msgMessage = handler.obtainMessage(2);
            msgMessage.arg1 = position;
            msgMessage.sendToTarget();
        }
    }

    /**
     * 发微博
     */
    protected void sendWeiBo(final int position, View v) {
        leixing = box.getLeixing();
        if (leixing.equals("addMicroPostF")) {
            AppContext.ADDMICROPOST = "addMicroPostF";
            addMicroPostF = box.getAddMicroPostF();
            AddMicroPostF a = new AddMicroPostF();
            a.setBody(addMicroPostF.getBody());
            a.setRecordId(addMicroPostF.getRecordId());
            a.setTargetId(addMicroPostF.getTargetId());
            a.setTargetType(addMicroPostF.getTargetType());
            a.setAddress(addMicroPostF.getAddress());
            a.setLatitude(addMicroPostF.getLatitude());
            a.setLongitude(addMicroPostF.getLongitude());
            a.setTaskIdOrEventId(addMicroPostF.getTaskIdOrEventId());
            try {
                String json = Json.toJson(a);
                new SendWeiBoTask().execute(json);
            } catch (Exception e) {
                Tools.handle(e);
            }
        } else if (leixing.equals("addMicroPostDMany")) {
            AppContext.ADDMICROPOST = "addMicroPostDMany";
            addMicroPostDMany = box.getAddMicroPostDMany();
            bbbb = new AddMicroPostDMany();
            bbbb.setBody(addMicroPostDMany.getBody());
            bbbb.setRecordId(addMicroPostDMany.getRecordId());
            bbbb.setAddress(addMicroPostDMany.getAddress());
            bbbb.setLatitude(addMicroPostDMany.getLatitude());
            bbbb.setLongitude(addMicroPostDMany.getLongitude());
            bbbb.setTaskIdOrEventId(addMicroPostDMany.getTaskIdOrEventId());
            bbbb.setTargetId(addMicroPostDMany.getTargetId());
            bbbb.setTargetType(addMicroPostDMany.getTargetType());
            String list = addMicroPostDMany.getList();
            pclist = list.split(",");
            pcpath = new ArrayList<String>();
            for (int i = 0; i < pclist.length; i++) {
                File file = new File(pclist[i]);
                if (file.exists()) {
                    pcpath.add(pclist[i]);
                }
            }
            final String[] imagepath = new String[pcpath.size()];
            final List<ManyImage> imglist = new ArrayList<ManyImage>();
            for (int i = 0; i < pcpath.size(); i++) {
                imagepath[i] = pcpath.get(i);
                ManyImage image = new ManyImage();
                image.setImgName(pcpath.get(i));
                image.setAddress("");
                image.setImgHeight("");
                image.setImgWidth("");
                image.setImgId("");
                image.setImgType("jpg");
                imglist.add(image);
            }
            if (pcpath.size() > 0) {// 有图
                ManyImage images = new ManyImage();
                images.setImgName(Tools.getTimeName(System.currentTimeMillis()));
                images.setAddress("");
                images.setImgHeight("");
                images.setImgWidth("");
                images.setImgId("");
                images.setImgType("jpg");
                // final String data=Json.toJson(images);
                final String data = Json.toJson(imglist);
                new Thread() {
                    public void run() {
                        try {
                            String result = null;
                            String Data = URLDecoder.decode(data, "UTF-8");
                            final String url = UrlTools.url
                                    + UrlTools.imgupload_path + Data
                                    + "&binding=" + AppContext.binding;
                            result = UploadImgManyClient.sendMany(imagepath,
                                    url);
                            if (result.equals("null") || result == null) {
                                wbhandler.sendEmptyMessage(-3);
                            } else {
                                Message msg = wbhandler.obtainMessage(1);
                                msg.obj = result;
                                msg.sendToTarget();
                            }
                        } catch (Exception e) {
                            Tools.handle(e);
                        }
                    }
                }.start();
            } else {// 没有图片
                wbhandler.sendEmptyMessage(2);
            }

        } else if (leixing.equals("addMicroPostL")) {
            AppContext.ADDMICROPOST = "addMicroPostL";
            addMicroPostL = box.getAddMicroPostL();
            AddMicroPostL c = new AddMicroPostL();
            c.setBody(addMicroPostL.getBody());
            c.setLinkName(addMicroPostL.getLinkName());
            c.setLinkValue(addMicroPostL.getLinkValue());
            c.setFiledata(addMicroPostL.getFiledata());
            c.setRecordId(addMicroPostL.getRecordId());
            c.setTargetId(addMicroPostL.getTargetId());
            c.setTargetType(addMicroPostL.getTargetType());
            c.setAddress(addMicroPostL.getAddress());
            c.setLatitude(addMicroPostL.getLatitude());
            c.setLongitude(addMicroPostL.getLongitude());
            c.setTaskIdOrEventId(addMicroPostL.getTaskIdOrEventId());
            String data = Json.toJson(c);
            new SendWeiBoTask().execute(data);
        } else if (leixing.equals("addMicroPostV")) {
            AppContext.ADDMICROPOST = "addMicroPostV";
            addMicroPostV = box.getAddMicroPostV();
            AddMicroPostV d = new AddMicroPostV();
            d.setBody(addMicroPostV.getBody());
            d.setRecordId(addMicroPostV.getRecordId());
            d.setTargetId(addMicroPostV.getTargetId());
            d.setTargetType(addMicroPostV.getTargetType());
            d.setPollOptions(addMicroPostV.getPollOptions());
            d.setAddress(addMicroPostV.getAddress());
            d.setLatitude(addMicroPostV.getLatitude());
            d.setLongitude(addMicroPostV.getLongitude());
            d.setTaskIdOrEventId(addMicroPostV.getTaskIdOrEventId());
            String data = Json.toJson(d);
            new SendWeiBoTask().execute(data);
        }
    }

    /**
     * 发评论
     */
    protected void sendComment() {
        leixing = box.getLeixing();
        if (leixing.equals("addMicroComment")) {
            comment = box.getComment();
            AddMicroComment d = new AddMicroComment();
            d.setBody(comment.getBody());
            d.setFeedid(comment.getFeedid());
            String json = Json.toJson(d);
            new SendCommentTask().execute(json);
        } else if (leixing.equals("addMicroCommentFile")) {
            // 带文件的评论
        }

    }

    class SendCommentTask extends AsyncTask<String, Void, String> {
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String data = params[0];
            String json;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("serviceName",
                    AppContext.ADDMICCOMMENT));
            pairs.add(new BasicNameValuePair("data", data));
            pairs.add(new BasicNameValuePair("binding", AppContext.binding));
            String url = UrlTools.url + UrlTools.url_path;
            json = NetWork.post(url, pairs);
            return json;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            try {
                if (result == null) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);


                    if ("en".equals(mEns)) {
                        Tools.showInfo(DraftBoxActivity.this, "Network exception, reply failed");
                    } else {
                        Tools.showInfo(DraftBoxActivity.this, "网络异常,回复失败");
                    }

                    return;
                }
                if (result.equals("outTime")) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    if ("en".equals(mEns)) {
                        Tools.showInfo(DraftBoxActivity.this, "The network is busy and the reply fails");
                    } else {
                        Tools.showInfo(DraftBoxActivity.this, "网络繁忙,回复失败");
                    }

                    return;
                }
                String code = ReturnCodeParser.getReturnCode(result);
                if (code.equals("-2")) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    DraftBoxActivity.this.finish();
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    if ("en".equals(mEns)) {
                        Tools.showInfo(DraftBoxActivity.this, "Login timeout, please log back in");
                    } else {
                        Tools.showInfo(DraftBoxActivity.this, "登陆超时,请重新登录");
                    }

                    return;
                }
                AddMicroCommentMessage msg = AddMicroCommentParser
                        .addmicrocommnet(result);
                boolean flag = msg.isResult();
                if (flag) {
                    db.deleteById(DraftBox.class, boxlist.get(listposition)
                            .getId());
                    db.deleteById(AddMicroComment.class,
                            boxlist.get(listposition).getId());
                    boxlist = db.findAllDraftBox(DraftBox.class);
                    adapter.changData(boxlist);
                    Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                    sendBroadcast(caogao);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    if ("en".equals(mEns)) {
                        Tools.showInfo(DraftBoxActivity.this, "Reply to success");
                    } else {
                        Tools.showInfo(DraftBoxActivity.this, "回复成功");
                    }

//                    DraftBoxActivity.this.finish();
                } else {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    if ("en".equals(mEns)) {
                        Tools.showInfo(DraftBoxActivity.this, "Reply failed, please operate later");
                    } else {
                        Tools.showInfo(DraftBoxActivity.this, "回复失败,请稍后操作");
                    }

                }
            } catch (Exception e) {
                Tools.handle(e);
            }
        }

    }

    /**
     * 发微博线程 * @author Administrator *
     */
    class SendWeiBoTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String data = params[0];
            String json = null;
            // String json=service.addMicroPost(data);
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("serviceName",
                    AppContext.ADDMICROPOST));
            pairs.add(new BasicNameValuePair("data", data));
            pairs.add(new BasicNameValuePair("binding", AppContext.binding));
            String url = UrlTools.url + UrlTools.url_path;
            json = NetWork.post(url, pairs);
            return json;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            try {
                if (result == null) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    Tools.showInfo(DraftBoxActivity.this, "网络异常,微贴发表失败");
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    // 使得p item 位置的按钮变得可点击
                    return;
                }
                if (result.equals("outTime")) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    Tools.showInfo(DraftBoxActivity.this, "网络繁忙,微贴发表失败");
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    return;
                }
                String code = ReturnCodeParser.getReturnCode(result);
                if (code.equals("-2")) {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    Tools.showInfo(DraftBoxActivity.this, "登陆超时,请重新登录");
                    return;
                }
                AddMicroPostMessage msg = AddMicroPostMessageParser
                        .addMicroPost(result);
                boolean flag = msg.isResult();
                if (flag) {
                    db.deleteById(DraftBox.class, boxlist.get(listposition)
                            .getId());
                    if (leixing.equals("addMicroPostF")) {
                        db.deleteById(AddMicroPostF.class,
                                boxlist.get(listposition).getId());
                    } else if (leixing.equals("addMicroPostDMany")) {
                        db.deleteById(AddMicroPostDMany.class,
                                boxlist.get(listposition).getId());
                    } else if (leixing.equals("addMicroPostL")) {
                        db.deleteById(AddMicroPostL.class,
                                boxlist.get(listposition).getId());
                    } else if (leixing.equals("addMicroPostV")) {
                        db.deleteById(AddMicroPostV.class,
                                boxlist.get(listposition).getId());
                    }
                    boxlist = db.findAllDraftBox(DraftBox.class);
                    adapter.changData(boxlist);
                    Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                    sendBroadcast(caogao);
                    Intent intent = new Intent(AppContext.INDEXADAPTER_SHUAXIN);
                    context.sendBroadcast(intent);
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                    Tools.showInfo(DraftBoxActivity.this, "微贴发表成功");
//                    DraftBoxActivity.this.finish();
                } else {
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    Tools.showInfo(DraftBoxActivity.this, "微贴发表失败！");
                    NotificationUtils.clearNotification(DraftBoxActivity.this,
                            p);
                }
            } catch (Exception e) {
                Tools.handle(e);
            }
        }

    }

    Handler wbhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String result = (String) msg.obj;
                    if (Tools.isNull(result)) {
                        boxlist.get(listposition).setClickable(true);
                        adapter.changData(boxlist);
                        NotificationUtils.clearNotification(context, p);
                        Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
                        return;
                    }
                    ImageInfo info = ImageParser.getImageInfo(result);
                    boolean isresult = info.isResult();
                    if (isresult) {
                        try {
                            String images = info.getImgId();
                            StringBuilder sb = new StringBuilder();
                            JSONArray array = new JSONArray(images);
                            for (int i = 0; i < array.length(); i++) {
                                sb.append(array.get(i) + ",");
                            }
                            String a = sb.toString();
                            bbbb.setFileIds(a.substring(0, a.length() - 1));
                            String data = Json.toJson(bbbb);
                            new SendWeiBoTask().execute(data);
                        } catch (Exception e) {
                            Tools.handle(e);
                        }
                    } else {
                        boxlist.get(listposition).setClickable(true);
                        adapter.changData(boxlist);
                        NotificationUtils.clearNotification(context, p);
                        Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
                        return;
                    }
                    break;

                case 2:// 没有图片
                    Tools.showInfo(context, "请选择图片");
                    break;
                case -3:
                    boxlist.get(listposition).setClickable(true);
                    adapter.changData(boxlist);
                    int a = msg.arg1;
                    NotificationUtils.clearNotification(context, p);
                    Tools.showInfo(context, "图片微贴失败！已保存草稿箱");
                    break;
            }
            super.handleMessage(msg);
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String result = (String) msg.obj;
                    int num = msg.arg1;
                    if (Tools.isNull(result)) {
                        NotificationUtils.clearNotification(context, num);
                        Tools.showInfo(context, "网络繁忙！签到失败");
                        return;
                    }
                    ImageInfo info = ImageParser.getImageInfo(result);
                    boolean isresult = info.isResult();
                    if (isresult) {
                        String images = info.getImgId();
                        String[] img = images.split(",");
                        for (int i = 0; i < img.length; i++) {
                            pzlist.add(img[i]);
                        }
                        addkhbf(num);
                    } else {
                        NotificationUtils.clearNotification(context, num);
                        Tools.showInfo(context, "网络繁忙！签到失败");
                    }
                    break;
                case 2:
                    int mesnum = msg.arg1;
                    addkhbf(mesnum);
                    break;
                case -3:
                    int messnum = msg.arg1;
                    NotificationUtils.clearNotification(context, messnum);
                    Tools.showInfo(context, "网络繁忙！签到失败");
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private DraftBoxDB db;
    private TextView empty;

    protected void addkhbf(final int num) {
        Khbf khbf = new Khbf();
        khbf.setBfkhccname(draftkhbf.getKehuName());
        khbf.setBfkh(draftkhbf.getKehuId());
        khbf.setBfzj(draftkhbf.getBfText());
        khbf.setBfsj(Tools.getTime(System.currentTimeMillis()));
        khbf.setBflx("临时拜访");
        if (pzlist.size() > 0) {
            for (int i = 0; i < 9; i++) {
                if (pzlist.size() < i + 1) {
                    pzlist.add("");
                }
            }
            khbf.setPz(pzlist.get(0));
            khbf.setPz1(pzlist.get(1));
            khbf.setPz2(pzlist.get(2));
            khbf.setPz3(pzlist.get(3));
            khbf.setPz4(pzlist.get(4));
            khbf.setPz5(pzlist.get(5));
            khbf.setPz6(pzlist.get(6));
            khbf.setPz7(pzlist.get(7));
            khbf.setPz8(pzlist.get(8));
        }
        khbf.setBfwz(draftkhbf.getBfwz());
        String jsonString = Json.toJson(khbf);
        String Data = null;
        try {
            Data = URLEncoder.encode(jsonString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            Tools.handle(e);
        }// 这个是对json数据转编码，必须的
        String url = UrlTools.url + UrlTools.url_path
                + "serviceName=insertWithRoleRight&objectApiName=khbf&data=["
                + Data + "]&binding=" + AppContext.binding;
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        boolean msg = KhbfParser
                                .getUpResult(responseInfo.result);
                        if (msg) {
                            try {
                                db.deleteById(DraftBox.class,
                                        boxlist.get(listposition).getId());
                                db.deleteById(DraftKhbf.class,
                                        boxlist.get(listposition).getId());
                                boxlist = db.findAllDraftBox(DraftBox.class);
                                adapter.changData(boxlist);
                            } catch (DbException e) {
                                Tools.handle(e);
                            }
                            if (boxlist.size() > 0) {
                                empty.setVisibility(View.GONE);
                                listView.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.VISIBLE);
                                listView.setVisibility(View.GONE);
                            }
                            Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                            sendBroadcast(caogao);
                            NotificationUtils.clearNotification(context, num);
                            Tools.showInfo(context, "签到成功！");
                        } else {
                            NotificationUtils.clearNotification(context, num);
                            Tools.showInfo(context, "签到失败！");
                        }
                    }

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        NotificationUtils.clearNotification(context, num);
                        Tools.showInfo(context, "签到失败！");
                    }
                });

    }

    @NonNull
    @Override
    public LayoutInflater getLayoutInflater() {
        return super.getLayoutInflater();
    }

    /**
     * 获取控件
     *
     * @throws DbException
     */
    private void setupView() throws DbException {
        SaveTemporaryData.mSmart = "";
        btnBtn = (Button) findViewById(R.id.btnBtn);
        btnBtn.setVisibility(View.INVISIBLE);
        backLayout = (LinearLayout) findViewById(R.id.backLayout);
        listView = (SwipeMenuListView) findViewById(R.id.caogaobox);
        empty = (TextView) findViewById(R.id.empty);
//        fanhui = (ImageView) findViewById(R.id.fanhui_caogao);
        db = new DraftBoxDB(context, UserManager.getManager().getUser().userId
                + "box.db");
//        SwipeMenuCreator creator = new SwipeMenuCreator() {
//
//            @Override
//            public void create(SwipeMenu menu) {
////				// create "open" item
////				SwipeMenuItem openItem = new SwipeMenuItem(
////						getApplicationContext());
////				// set item background
////				openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
////						0xCE)));
////				// set item width
////				openItem.setWidth(dp2px(90));
////				// set item title
////				openItem.setTitle("Open");
////				// set item title fontsize
////				openItem.setTitleSize(18);
////				// set item title font color
////				openItem.setTitleColor(Color.WHITE);
////				// add to menu
////				menu.addMenuItem(openItem);
//
//                // create "delete" item
//                SwipeMenuItem deleteItem = new SwipeMenuItem(
//                        getApplicationContext());
//                // set item background
//                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xE4, 0x35,
//                        0x20)));
//                // set item width
//                deleteItem.setWidth(dp2pxx(86));
//                // set a icon
//                deleteItem.setIcon(R.drawable.delete_slidelist);
//                // add to menu
//                menu.addMenuItem(deleteItem);
//            }
//        };


        if (db.isExit()) {
            empty.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            boxlist = db.findAllDraftBox(DraftBox.class);
            adapter = new DraftBoxAdapter(boxlist, this);

            listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
//            listView.setMenuCreator(creator);
            listView.setAdapter(adapter);
//            setBtnColor(boxlist);
        } else {
            empty.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
//            setBtnColor(boxlist);
        }
        iSlistEmpty();
    }

    public void iSlistEmpty() {

        backLayout.setBackgroundColor(Color.rgb(244, 246, 249));


    }


    public int dp2pxx(float dipValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public void setBtnColor(List<DraftBox> boxlist) {
        btnBtn.setBackgroundResource(R.drawable.a_shap_range_caogao);
        btnBtn.setTextColor(Color.rgb(140, 140, 140));
        if (boxlist.isEmpty() && boxlist.size() == 0) {
            btnBtn.setBackgroundResource(R.drawable.a_shap_range_caogao);
        } else {
            btnBtn.setTextColor(Color.rgb(12, 119, 212));
            btnBtn.setBackgroundResource(R.drawable.a_shape_replay_btn);
        }
    }

    public void allShow() {
        AllHintBtn();
        isBool = false;
        btnBtn.setText("完成");
        btnBtn.setTextColor(Color.WHITE);
        btnBtn.setBackgroundResource(R.drawable.a_shape_blue);
        for (int i = 0; i < boxlist.size(); i++) {
            adapter.setImage(i, true);
        }
        adapter.notifyDataSetChanged();
    }

    public void allHint() {
        AllShowBtn();
        isBool = true;
        btnBtn.setText("编辑");
        btnBtn.setTextColor(Color.rgb(12, 119, 212));
        btnBtn.setBackgroundResource(R.drawable.a_shape_replay_btn);
        for (int i = 0; i < boxlist.size(); i++) {
            adapter.setImage(i, false);
        }
        adapter.notifyDataSetChanged();
    }

    public void AllShowBtn() {//open
        for (int i = 0; i < boxlist.size(); i++) {
            if (!adapter.getBtn(i)) {
                adapter.setBtn(i, true);

            }
        }

        adapter.notifyDataSetChanged();
    }

    public void AllHintBtn() {//close
        for (int i = 0; i < boxlist.size(); i++) {
            if (adapter.getBtn(i)) {
                adapter.setBtn(i, false);
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {

        if ("deleteItems".equals(SaveTemporaryData.mSmart)) {
            if (!"".equals(SaveTemporaryData.DraftBoxPosition)){
//                deleteItem(Integer.valueOf(SaveTemporaryData.DraftBoxPosition));
                deleteItem(deletePosition);
            }
            SaveTemporaryData.DraftBoxPosition = "";
            SaveTemporaryData.mSmart = "";
        }


        super.onResume();
    }

    //**
//        * 中间弹出PopupWindow
//*
//        *  设置PopupWindow以外部分有一中变暗的效果
//* @param view  parent view
//*/
    public void showCenterPopupWindow(View view, final int position) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_layout, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        TextView tvTitle = (TextView) contentView.findViewById(R.id.tv_title);
        TextView tvConfirm = (TextView) contentView.findViewById(R.id.OneItem);
        TextView tvCancel = (TextView) contentView.findViewById(R.id.AllItem);
//        tvTitle.setText("标为已读");
        tvConfirm.setText("删除草稿");
        tvCancel.setText("清空草稿箱");

//        tvTitle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(DraftBoxActivity.this, "标为已读", Toast.LENGTH_SHORT).show();
//                popupWindow.dismiss();
//            }
//        });

        tvConfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteItem(position);
                popupWindow.dismiss();
            }
        });

        tvCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAllItem();
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        // 设置PopupWindow以外部分的背景颜色  有一种变暗的效果
        final WindowManager.LayoutParams wlBackground = getWindow().getAttributes();
        wlBackground.alpha = 0.5f;      // 0.0 完全不透明,1.0完全透明
        getWindow().setAttributes(wlBackground);
        // 当PopupWindow消失时,恢复其为原来的颜色
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                wlBackground.alpha = 1.0f;
                getWindow().setAttributes(wlBackground);
            }
        });
        //设置PopupWindow进入和退出动画
        popupWindow.setAnimationStyle(R.style.anim_popup_centerbar);
        // 设置PopupWindow显示在中间
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

    }
}
